package com.inpion.biz.broker.service.util;

import java.util.Map;
import java.util.Set;

import com.inpion.biz.broker.service.data.DataResult;
import com.inpion.biz.broker.service.data.DataStore;
import com.inpion.biz.broker.service.handler.IDataProvider;
import com.inpion.biz.broker.service.info.HandlerInfo;
import com.inpion.biz.broker.service.listener.DataStoreListener;

public class DataStoreService {
	
	private static String providerId;
	private static final String DOT = DataStore.DOT;
	
	public static IDataProvider getProvider(String repositoryId) {
		providerId = repositoryId;
		
		HandlerInfo handlerInfo = (HandlerInfo) DataStoreListener.getInformation(repositoryId).get(DataStore.HANDLER);
		System.out.println("handler information: " + handlerInfo);

		String handlerKey = null;
		Set<String>keySet = handlerInfo.keySet();
		for(String key: keySet) {
			if(key.endsWith(DOT + repositoryId)) {
				handlerKey = key;
				System.out.println("handlerKey: " + handlerKey);
			}
		}
		
		Class<?>klass = (Class<?>) handlerInfo.get(handlerKey);
		try {
			return (IDataProvider) klass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static DataResult execute(IDataProvider provider) {
		
		Map<String, Object>databaseCollection = (Map<String, Object>) DataStoreListener.getInformation(providerId);
		
		provider.setParamObject(DataStore.CONNECTION, databaseCollection.get(DataStore.CONNECTION) );
		
		System.out.println("command id: " + provider.getParamObject(DataStore.COMMAND) );
		String command = buildCommand(provider);
		System.out.println("builded command: " + command);
		
		return processCommand(provider, command);
	}
	
	private static String buildCommand(IDataProvider provider) {
		
		String command = (String) provider.getParamObject(DataStore.COMMAND);
		
		String queryString = DataStoreListener.getCommand(providerId, command);
		
		return queryString;
	}

	private static DataResult processCommand(IDataProvider provider, String command) {

		provider.execute(command);
		
		return provider.returnDataResult();
	}

}
